package com.cartoon.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cartoon.R;
import com.cartoon.adapter.KKCarttonReadingContentAdapter;
import com.cartoon.databinding.KkCarttonReadingActivityBinding;
import com.cartoon.model.CartoonDataViewModel;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import anime.play.room.AnimePlayHistoryModel;
import anime.play.room.AnimePlayHistoryViewModel;
import base.QActivity;
import cartoon.room.read.room.CartoonReadHistoryModel;
import cartoon.room.read.room.CartoonReadHistoryViewModel;
import constant.AppConstants;
import http.Api;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import model.CarttonKKContentModel;
import model.CarttonKKDirectoryModel;
import model.CarttonKKHistrory;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class KKCarttonReadingActivity extends QActivity {
    private int kkCartoonId;
    private KkCarttonReadingActivityBinding binding;
    private KKCarttonReadingContentAdapter kkcarttonReadingContentAdapter;
    List<CarttonKKDirectoryModel.DataBean.TopicInfoBean.ComicsBean> kkListData;
    private RecyclerView.OnScrollListener loadingMoreListener;
    private int timeOut;
    private boolean next = true;
    private Disposable disposable;
    private CartoonReadHistoryViewModel viewModel;
    private String kkname;
    private String kktitle;
    private List<CarttonKKHistrory> kkHistrory;


    @Override
    public int getLayoutRes() {
        return R.layout.kk_cartton_reading_activity;
    }

    @Override
    public void initView() {
        binding = DataBindingUtil.setContentView(this, getLayoutRes());
        Bundle bundle = getIntent().getExtras();
        kkCartoonId = bundle.getInt("kkCartoonId", 0);
        kkname = bundle.getString("kkname");

    }

    @Override
    public void initData() {

        viewModel = new ViewModelProvider(this).get(CartoonReadHistoryViewModel.class);


        LinearLayoutManager kkManager = new LinearLayoutManager(this);
        kkManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvKkreading.setLayoutManager(kkManager);//kk_cartton_reading_content_item
        kkcarttonReadingContentAdapter = new KKCarttonReadingContentAdapter(R.layout.kk_cartton_reading_content_item, null);
        binding.rvKkreading.setAdapter(kkcarttonReadingContentAdapter);
    }

    @Override
    public void initListener() {


        CartoonDataViewModel.getInstance().getKKData().observe(this, new Observer<List<CarttonKKDirectoryModel.DataBean.TopicInfoBean.ComicsBean>>() {
            @Override
            public void onChanged(List<CarttonKKDirectoryModel.DataBean.TopicInfoBean.ComicsBean> comicsBeans) {
                kkListData = comicsBeans;
            }
        });



        CartoonDataViewModel.getInstance().getKKHistroryData().observe(this, new Observer<List<CarttonKKHistrory>>() {
            @Override
            public void onChanged(List<CarttonKKHistrory> carttonKKHistrory) {
                kkHistrory = carttonKKHistrory;
            }
        });


        binding.ivBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        loadingMoreListener = new RecyclerView.OnScrollListener() {
            //到达顶部和底部监听
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // OnScrollListener.SCROLL_STATE_FLING; //屏幕处于甩动状态
                // OnScrollListener.SCROLL_STATE_IDLE; //停止滑动状态
                // OnScrollListener.SCROLL_STATE_TOUCH_SCROLL;// 手指接触状态
                // 记录当前滑动状态



                if(kkListData!=null && kkListData.size()>=1){

                    if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当前状态为停止滑动
                        if (!binding.rvKkreading.canScrollVertically(1)) { // 到达底部
                            ToastUtils.showLong("请稍后再下拉刷新");

                            for (int i = 0; i < kkListData.size(); i++) {
                                if (kkListData.get(i).getId().equals(kkCartoonId)) {
                                    if (i + 1 < kkListData.size()) {
                                        if (timeOut == 1) {
                                            timeOut = 5;
                                            next = true;
                                            //          LogUtils.d("开发开发看A" + i + "---->" + kkListData.size());
                                            getKKCartoonContent(kkListData.get(i + 1).getId());
                                            kkCartoonId = kkListData.get(i + 1).getId();
                                            return;
                                        }
                                    }

                                }
                            }
                        } else if (!binding.rvKkreading.canScrollVertically(-1)) { // 到达顶部
                            for (int i = 0; i < kkListData.size(); i++) {
                                if (kkListData.get(i).getId().equals(kkCartoonId)) {
                                    if (i - 1 >= 0) {
                                        if (timeOut == 1) {
                                            timeOut = 5;

                                            next = false;
                                            //      LogUtils.d("开发开发看B" + i + "---->" + kkListData.size());
                                            getKKCartoonContent(kkListData.get(i - 1).getId());
                                            kkCartoonId = kkListData.get(i - 1).getId();
                                            return;
                                        }

                                    }

                                }
                            }
                            ToastUtils.showLong("请稍后再上拉刷新");
                        }
                    }


                } else if(kkHistrory!=null && kkHistrory.size()>1){


                    if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当前状态为停止滑动
                        if (!binding.rvKkreading.canScrollVertically(1)) { // 到达底部
                            ToastUtils.showLong("请稍后再下拉刷新");

                            for (int i = 0; i < kkHistrory.size(); i++) {
                                if (kkHistrory.get(i).getId().equals(kkCartoonId)) {
                                    if (i + 1 < kkHistrory.size()) {
                                        if (timeOut == 1) {
                                            timeOut = 5;
                                            next = true;
                                            //          LogUtils.d("开发开发看A" + i + "---->" + kkListData.size());
                                            getKKCartoonContent(kkHistrory.get(i + 1).getId());
                                            kkCartoonId = kkHistrory.get(i + 1).getId();
                                            return;
                                        }
                                    }

                                }
                            }
                        } else if (!binding.rvKkreading.canScrollVertically(-1)) { // 到达顶部
                            for (int i = 0; i < kkHistrory.size(); i++) {
                                if (kkHistrory.get(i).getId().equals(kkCartoonId)) {
                                    if (i - 1 >= 0) {
                                        if (timeOut == 1) {
                                            timeOut = 5;

                                            next = false;
                                            //      LogUtils.d("开发开发看B" + i + "---->" + kkListData.size());
                                            getKKCartoonContent(kkHistrory.get(i - 1).getId());
                                            kkCartoonId = kkHistrory.get(i - 1).getId();
                                            return;
                                        }

                                    }

                                }
                            }
                            ToastUtils.showLong("请稍后再上拉刷新");
                        }
                    }
                }


            }


            //上滑下滑监听
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < 0) { // 当前处于上滑状态

                } else if (dy > 0) { // 当前处于下滑状态

                }
            }
        };

        binding.rvKkreading.addOnScrollListener(loadingMoreListener);

    }

    @Override
    public void networkMessage() {
        getKKCartoonContent(kkCartoonId);
    }

    public void getKKCartoonContent(int id) {

        Call<CarttonKKContentModel> call = Api.getInstance().service.getKKCartoonContent(id);
        call.enqueue(new Callback<CarttonKKContentModel>() {
            @Override
            public void onResponse(Call<CarttonKKContentModel> call, Response<CarttonKKContentModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {


                    setTime();

                    timeOut = 2;
                    CarttonKKContentModel.DataBean data = response.body().getData();
                    binding.rvKkreading.scrollToPosition(0);


                    binding.tvTitle.setText(data.getComic_info().getTitle());
                    kktitle = data.getComic_info().getTitle();
//                    if (next) {
//                        LogUtils.d("开发开发看W");
//                        //下一话的时候就重0位置开始看
//                        binding.rvReading.scrollToPosition(0);
//
//                    } else {
//                        LogUtils.d("开发开发看Q" + data.getComic_info().getImages().size());
//                        //上一话的时候就重最后的位置开始看
//                        binding.rvReading.scrollToPosition(data.getComic_info().getImages().size() - 2);
//
//                    }


//                    carttonReadingContentAdapter.replaceData(data.getComic_info().getImages());
                    kkcarttonReadingContentAdapter.replaceData(data.getComic_info().getComic_images());

                    int animePlayHistory = SPStaticUtils.getInt("KKCarttonHistory", 0);
                    int newId = animePlayHistory + 1;
                    LogUtils.d("保存的Id" + newId);
                    SPStaticUtils.put("KKCarttonHistory", newId);


                    if(kkListData!=null && kkListData.size()>=1){
                        GsonUtils.toJson(kkListData);
                        viewModel.addHistoryDao(new CartoonReadHistoryModel(newId, 2, kkCartoonId, GsonUtils.toJson(kkListData), kkname, kktitle, kkListData.get(0).getCover_image_url(),null));
                        viewModel.getAllSLive().getValue();
                    } else if(kkHistrory!=null && kkHistrory.size()>1){
                        GsonUtils.toJson(kkHistrory);
                        viewModel.addHistoryDao(new CartoonReadHistoryModel(newId, 2, kkCartoonId, GsonUtils.toJson(kkHistrory), kkname, kktitle, kkHistrory.get(0).getCover_image_url(),null));
                        viewModel.getAllSLive().getValue();
                    }


                } else {
                    if (response.body() != null && response.body().getMessage() != null) {
                        ToastUtils.showLong(response.body().getMessage() + "状态码:" + response.code());
                    }
                }


            }

            @Override
            public void onFailure(Call<CarttonKKContentModel> call, Throwable t) {
                LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());

            }
        });
    }


    public void setTime() {
        stopDisposable(disposable);
        disposable = Flowable.timer(1 * 5000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                        timeOut = 1;

                    }
                });
    }


    /**
     * 关闭定时器
     *
     * @param disposable 定时器
     */
    private void stopDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        stopDisposable(disposable);
    }
}
